// 服务地址
var uploadGPSPosUrl = getGPSDomain() + '/wxweb/uploadGPSPos'
var geocoderUrl = 'https://apis.map.qq.com/ws/geocoder/v1/'
var qqKey = 'XKGBZ-ZWY2J-ARQFP-FPGU6-HCCC2-T3BZM'

// 格式化日期字符串
function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  if (month < 10) {
    month = "0" + month;
  }
  var day = date.getDate()
  if (day < 10) {
    day = "0" + day;
  }

  var hour = date.getHours()
  if (hour < 10) {
    hour = "0" + hour;
  }
  var minute = date.getMinutes()
  if (minute < 10) {
    minute = "0" + minute;
  }
  var second = date.getSeconds()
  if (second < 10) {
    second = "0" + second;
  }

  return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
}

function getGPSDomain() {
  return 'https://gps.dituhui.com'
}

// 同步
function getStorage(key) {
  var value = wx.getStorageSync(key)
  return value
}

// 异步
function setStorage(key, value) {
  wx.setStorage({
    key: key,
    data: value
  })
}

function uploadGPS(nickName) {
  wx.getLocation({
    type: 'gcj02',
    success: function (locationData) {
      var latitude = locationData.latitude
      var longitude = locationData.longitude
      // 存入全局变量
      var app = getApp()
      app.coord = longitude + "," + latitude
      console.log("coord = " + app.coord)
      var accuracy;
      if (locationData.accuracy) {
        accuracy = locationData.accuracy;
      } else {
        accuracy = -1;
      }
      var time = formatTime(new Date())
      //console.log("data:" + longitude + "," + latitude + "," + accuracy + "," + time)

      // 是否坐标精度
      if (accuracy > 0) {
        var groupId = ''
        var phone = ''
        if (app.phone) {
          phone = app.phone
        }
        if (app.groupId) {
          // 优先从内存对象取值
          groupId = app.groupId
        } else {
          // 再从系统缓存里取值
          var groutInfo = getStorage('groutInfo')
          if (groutInfo != null) {
            groupId = groutInfo.groupId
            // 取groupId的时候也取phone
            phone = groutInfo.phone
          }
        }
        console.log("(gpsData)groupId=" + groupId)
        var gpsData = longitude + "^" + latitude + "^" + accuracy + "^" + time + "^" + groupId + "^" + phone;
        // var gpsDatas;
        // if (app.reuploadGps.length == 0) {
        //   gpsDatas = gpsData;
        // } else {
        //   gpsDatas = "";
        //   var i;
        //   for (i = 0; i < app.reuploadGps.length; i++) {
        //     gpsDatas += app.reuploadGps[i] + "__";
        //   }
        //   gpsDatas += gpsData;
        // }
        // 上传坐标
        wx.request({
          url: uploadGPSPosUrl,
          data: {
            a: nickName,
            cmd: 'upload',
            type: 'basket',
            g: gpsData
          },
          success: function (uploadGPSResult) {
            console.log("success:" + uploadGPSResult.data)
            if (!uploadGPSResult.data.indexOf("成功")) {
              console.log("记录补传数据")
              app.reuploadGps[app.reuploadGps.length] = gpsData
            } else {
              // 上传成功后清理补传数据
              app.reuploadGps = new Array()
            }
          },
          fail: function (uploadGPSFailedResult) {
            logToServer(app.nickName, 'uploadGPSFailed')
            console.log("fail:" + uploadGPSFailedResult);
            console.log("记录补传数据")
            app.reuploadGps[app.reuploadGps.length] = gpsData
          }
        });
      } else {
        console.log("坐标精度(" + accuracy + ")低，不上传。");
      }
    },
    fail: function (e) {
      var app = getApp()
      app.coord = "0,0"
      console.log('getLocation fail', e)
    }
  })
}

function getAddr(x, y, handleGetAddr) {
  wx.request({
    url: geocoderUrl,
    data: {
      location: y + ',' + x,
      key: qqKey
    },
    success: function (geocodeResult) {
      console.log("success:" + geocodeResult.data)
      if (geocodeResult.data.status == 0) {
        var address = geocodeResult.data.result.address
        handleGetAddr(address)
        console.log("address: " + address)
      } else {
        console.log("获取地址失败")
      }
    },
    fail: function (geocodeResult) {
      console.log("获取地址失败")
    }
  });
}

function geocode(addr, handleGeocode) {
  wx.request({
    url: geocoderUrl,
    data: {
      address: addr,
      key: qqKey
    },
    success: function (geocodeResult) {
      console.log("success:" + geocodeResult.data)
      if (geocodeResult.data.status == 0) {
        var location = geocodeResult.data.result.location
        console.log("geocode: " + location.lng + ',' + location.lat)
        handleGeocode(location.lng, location.lat)
      } else {
        console.log("地址查询失败")
      }
    },
    fail: function (geocodeResult) {
      console.log("地址查询失败")
    }
  });
}

function isVersionValid(version, validVersion){
  var arrVersion = version.split(".")
  var arrValidVersion = validVersion.split(".")
  if (arrVersion[0] > arrValidVersion[0]){
    return true
  } else if (arrVersion[0] == arrValidVersion[0]){
    if (arrVersion[1] > arrValidVersion[1]) {
      return true
    } else if (arrVersion[1] == arrValidVersion[1]) {
      if (arrVersion[2] >= arrValidVersion[2]) {
        return true
      }
    }
  }
  return false
}

module.exports = {
  formatTime: formatTime,
  getAddr: getAddr,
  geocode: geocode,
  getGPSDomain: getGPSDomain,
  uploadGPS: uploadGPS,
  setStorage: setStorage,
  getStorage: getStorage,
  isVersionValid: isVersionValid
}

